package dao

import (
	"pojo/model"

	"github.com/jinzhu/gorm"
	"pojo/form"
)

// 管理员数据库访问对象
type AdminDao struct {
	db *gorm.DB
}

// 构造AdminDao需要传入数据库对象
func NewAdminDao(db *gorm.DB) *AdminDao {

	return &AdminDao{
		db: db,
	}
}

// 保存管理员信息
func (this *AdminDao) InsertAdmin(admin *model.Admin) (int64, error) {

	result := this.db.Save(admin)

	return result.RowsAffected, result.Error
}

// 根据用户名查询管理员
func (this *AdminDao) GetAdmin(username string) (*model.Admin, error) {

	admin := &model.Admin{}

	result := this.db.Find(admin, "username = ?", username)

	return admin, result.Error
}

//根据ID删除管理员
func (this *AdminDao) DeleteAdmin(id uint64) (error) {

	result := this.db.Delete(model.Admin{}, "id = ?", id)

	return result.Error
}

// 根据Id查询管理员
func (this *AdminDao) GetAdminById(id uint64) (*model.Admin) {

	admin := &model.Admin{}

	this.db.Find(admin, "id = ?", id)

	return admin
}

// 修改管理员信息
func (this *AdminDao) UpdateAdmin(admin *model.Admin) (int64, error) {

	result := this.db.Model(&admin).Updates(model.Admin{Password: admin.Password, Username: admin.Username})

	return result.RowsAffected, result.Error
}

// 统计管理数量
func (this *AdminDao) Count() uint64 {

	var size uint64

	this.db.Model(model.Admin{}).Count(&size)

	return size
}

// 查询管理列表
func (this *AdminDao) List(query *form.AdminPageQueryForm) ([]model.Admin) {

	admins := make([]model.Admin, 0)

	offset := (query.Page - 1) * query.Limit

	this.db.Model(model.Admin{}).Offset(offset).Limit(query.Limit).Find(&admins)

	return admins
}
